<template>
  <!-- 主容器 -->
  <div class="common-wrap" style="display: flex; flex-direction: column">
    <div>
      <!-- 模板导航栏 -->
      <h4 class="section-title">{{ $t("导入模板") }}</h4>
      <el-divider style="margin: 5px 0" />
      <div class="nav-template">
        <!-- 循环渲染模板列表 -->
        <el-checkbox-group v-model="checkList" @change="handleCheckChange">
          <div class="flex-weap">
            <div
              v-for="item in temList"
              :key="item.templateCode"
              class="flex-center"
              style="margin-right: 10px"
            >
              <!-- 将名称从el-checkbox内部移出 -->
              <el-checkbox :value="item.templateCode"></el-checkbox>
              <div>
                <span
                  class="template-name"
                  :style="{
                    color:
                      fieldObj.templateCode === item.templateCode
                        ? 'red'
                        : '#409eff',
                    fontSize: '14px',
                    lineHeight: 1,
                    cursor: 'pointer',
                  }"
                  @click="handleTemplateClick(item)"
                  >{{ $t(item.templateName) }}</span
                >
              </div>
            </div>
          </div>
        </el-checkbox-group>
      </div>
      <div
        style="
          display: flex;
          align-items: baseline;
          height: 25px;
          justify-content: space-between;
        "
      >
        <h4 class="section-title">{{ $t("字段列") }}</h4>
        <div class="settings-icon">
          <el-button
            type="text"
            style="padding: 5px 14px; height: 22px"
            @click="drawer = !drawer"
            >{{ $t("字段设置") }}</el-button
          >
          <el-button
            type="text"
            style="padding: 5px 14px; height: 22px"
            @click="onSave"
            >{{ $t("数据生成") }}</el-button
          >
          <el-upload
            v-model:file-list="fileList"
            action=""
            multiple
            :auto-upload="false"
            :on-change="handleChange"
            :show-file-list="false"
          >
            <el-button type="text" style="padding: 5px 14px; height: 22px">{{
              $t("文件上传")
            }}</el-button>
          </el-upload>
        </div>
      </div>
      <el-divider style="margin: 5px 0" />
      <div
        class="field-template"
        :title="`
| 先取左在取右
+ 加
- 减
* 乘
/ 除
, 合并分割 |;分割符
@ 空格分割
# 几行几列
: 某表某值
n(*^1) 1*2*3 取1
      `"
      >
        <div class="flex-weap">
          <div class="field-item">
            <span class="field-label">{{ $t("主数据表") }}：</span>
            <span class="field-value">{{ fieldObj.mainTableIndex }}</span>
          </div>
          <div class="field-item">
            <span class="field-label">{{ $t("有效行数据") }}：</span>
            <span class="field-value">{{ fieldObj.leastData }}</span>
          </div>
          <div class="field-item">
            <span class="field-label">{{ $t("表关联规则") }}：</span>
            <span class="field-value">{{ fieldObj.multiSheetRules }}</span>
          </div>

          <div
            v-for="item in fieldObj.importTemplateDetailsList"
            :key="item.field"
            class="field-item"
          >
            <span class="field-label">{{ $t(item.fieldName) }}：</span>
            <span class="field-value">{{ item.rules }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 滚动条容器 -->
    <div style="flex: 1; overflow: hidden">
      <el-scrollbar>
        <!-- 循环渲染多个表格 -->
        <div
          v-for="(item, index) in tableList"
          :key="index"
          class="table-container"
        >
          <!-- 表格标题栏 -->
          <div class="table-title">
            <!-- 工作簿名称 -->
            <span class="title-item">
              <span>工作薄：</span>
              <span class="highlight-text">{{ item.fileName }}</span>
            </span>

            <!-- 表名 -->
            <span class="title-item">
              <span>表名：</span>
              <span class="highlight-text">{{ item.sheetName }}</span>
            </span>

            <!-- 表序号和表头位置 -->
            <span class="title-item">
              <span>表序:</span>
              <span class="index-number">{{ index + 1 }}</span>
              <span>表头位置：</span>
              <span class="index-number">{{ item.headersPosition }}</span>
            </span>

            <!-- 显示/隐藏按钮 -->
            <span class="toggle-button" @click="toggleOmit(item)">
              <el-icon v-show="item.omit"><Hide /></el-icon>
              <el-icon v-show="!item.omit"><View /></el-icon>
            </span>

            <!-- 隐藏范围设置 -->
            <span class="range-control">
              <span class="range-label">隐藏范围：</span>
              <el-input-number
                v-model="item.minOmit"
                :controls="false"
                class="range-input"
              />
              <span class="range-separator">-</span>
              <el-input-number
                v-model="item.maxOmit"
                :controls="false"
                class="range-input"
              />
            </span>
          </div>

          <!-- 表格主体 -->
          <table class="native-table">
            <!-- 表头 -->
            <thead>
              <tr>
                <th
                  v-for="(header, headerIndex) in item.headers"
                  :key="`${headerIndex}${index}`"
                  :title="`${header || ''}`"
                  class="table-header"
                >
                  <!-- 列索引和列名 -->
                  <span class="column-index">{{
                    header === "序号" ? "" : headerIndex - 1
                  }}</span
                  >{{ header }}
                </th>
              </tr>
            </thead>

            <!-- 表格内容 -->
            <tbody>
              <template
                v-for="(row, rowIndex) in item.tableData"
                :key="`row-${index}-${rowIndex}`"
              >
                <!-- 正常显示的行 -->
                <tr class="table-row" v-if="isTypeOmit(item, row[0])">
                  <td
                    v-for="(header, colIndex) in item.headers"
                    :key="`cell-${index}-${rowIndex}-${colIndex}`"
                    :title="`${row[colIndex] || ''}`"
                    class="table-cell"
                  >
                    <!-- 图片渲染 -->
                    <el-image
                      v-if="imgType(item, row, colIndex)"
                      :src="row[colIndex]"
                      alt="图片"
                      class="preview-image"
                      :preview-src-list="[row[colIndex]]"
                    >
                      {{ row[colIndex] }}
                    </el-image>
                    <!-- 文本渲染 -->
                    <span v-else>{{ row[colIndex] }}</span>
                  </td>
                </tr>

                <!-- 省略行标记 -->
                <tr
                  class="table-row"
                  v-if="row[0] === item.maxOmit && item.omit"
                >
                  <td
                    v-for="(header, colIndex) in item.headers"
                    :key="`cell-${index}-${rowIndex}-${colIndex}`"
                    class="table-cell"
                  >
                    <el-icon v-if="!colIndex"><MoreFilled /></el-icon>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
        </div>
      </el-scrollbar>
    </div>
    <el-drawer v-model="drawer" :title="$t('字段配置')" size="42%">
      <el-row :gutter="10">
        <el-col :span="4">
          <div class="flex-column" style="margin-bottom: 10px">
            <span style="margin: 5px 0">{{ $t("主数据表") }}</span>
            <el-input-number
              style="width: 100%"
              size="default"
              :min="0"
              v-model="fieldObj.mainTableIndex"
              :controls="false"
            />
          </div>
        </el-col>
        <el-col :span="4">
          <div class="flex-column" style="margin-bottom: 10px">
            <span style="margin: 5px 0">{{ $t("有效行数据") }}</span>
            <el-input
              style="flex: 1"
              size="default"
              v-model="fieldObj.leastData"
              :controls="false"
            />
          </div>
        </el-col>
        <el-col :span="16">
          <div class="flex-column" style="margin-bottom: 10px">
            <span style="margin: 5px 0">{{ $t("表关联规则") }}</span>
            <el-input
              style="flex: 1"
              size="default"
              v-model="fieldObj.multiSheetRules"
              :controls="false"
            />
          </div>
        </el-col>
        <el-col
          v-for="(item, index) in fieldObj.importTemplateDetailsList"
          :key="`${index}_${item.field}`"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <div
            class="flex-column"
            style="
              border: 1px solid #cccccc4d;
              padding: 5px;
              border-radius: 5px;
              margin-bottom: 5px;
            "
          >
            <span style="margin: 5px 0">{{ $t(item.fieldName) }}</span>
            <el-input
              :title="item.rules"
              style="flex: 1"
              size="default"
              v-model="item.rules"
              :controls="false"
            />
          </div>
        </el-col>
      </el-row>
    </el-drawer>
  </div>
</template>

<script setup>
// 导入模块
import * as str from "./index.js"; // 导入数据
import { onMounted, ref } from "vue"; // 导入Vue钩子和响应式API
import { ElMessage } from "element-plus";
import * as api from "@/api/index.js";
import { useRoute } from "vue-router";
import { debounce } from "@/utils/mUtils";
const route = useRoute();
// 响应式数据
const tableList = ref([]); // 表格数据列表
const temList = ref([]); // 模板列表
const fieldObjList = ref([]); // 字段对象列表
const fieldObj = ref({}); // 字段列表
const checkList = ref([]); // 选中的模板列表
const drawer = ref(false); // 抽屉状态
const fileList = ref([]); // 文件列表
const conentData = ref(); // 文件内容
defineOptions({
  name: "Template",
});
/**
 * 数据处理函数
 * 将原始数据转换为表格所需的格式
 */
const list = () => {
  // 转换每个数据项
  tableList.value = conentData.value.map((dataItem) => {
    // 初始化变量
    let headers = []; // 表头数组
    let headersPosition = 0; // 表头位置
    const tableData = []; // 表格数据
    const imgs = []; // 图片列索引数组
    let maxHeaderLength = 0; // 最大表头长度
    let processedHeader = false; // 是否处理过表头
    const numericHeaderRegex = /^[\d.]+$/; // 数字表头正则

    // 处理数据列表
    dataItem.dataList.forEach((row, rowIndex) => {
      // 检查是否为数字表头行
      const dataeaders = row.some(
        (header) => header && numericHeaderRegex.test(header)
      );
      // 计算非空值数量
      const rowEmpty = row.filter((it) => it);
      const headersEmpty = headers.filter((it) => it);

      // 找到最长的头部行作为表头
      if (rowEmpty.length > headersEmpty.length && !dataeaders) {
        headers = [...row];
        headers.unshift("序号"); // 添加序号列
        maxHeaderLength = row.length;
        headersPosition = rowIndex + 1;
        processedHeader = false;
      }

      // 动态扩展表头长度
      if (row.length > maxHeaderLength) {
        row.length - maxHeaderLength > 0 &&
          headers.push(...Array(row.length - maxHeaderLength).fill(""));
        maxHeaderLength = row.length;
      }

      // 处理数据行
      let dataArr = [rowIndex + 1, ...row]; // 添加行号

      // 特殊处理表头数据行
      if (
        !processedHeader &&
        !dataeaders &&
        headers.length > fieldObj.value.leastData
      ) {
        if (tableData.length >= fieldObj.value.leastData) {
          dataArr = [rowIndex + 1, ...row];
        } else {
          dataArr = [rowIndex + 1, ...Array(row.length).fill("")];
        }
        processedHeader = true;
      }

      // 将行数据添加到表格数据中
      tableData.push(dataArr);
    });

    // 处理图片数据
    if (
      tableData.length > 0 &&
      dataItem.pictures &&
      dataItem.pictures.length > 0
    ) {
      dataItem.pictures.forEach((picData) => {
        // 计算实际的行索引
        const targetRowIndex = picData.rowIndex ? picData.rowIndex : 0;

        // 确保目标行存在
        if (targetRowIndex < 0 || targetRowIndex >= tableData.length) return;

        // 动态扩展表头（如果需要）
        const requiredCols = Math.max(picData.colIndex + 3, headers.length);
        while (headers.length < requiredCols) {
          headers.push(headers.length.toString());
        }

        // 尝试放置图片数据到合适的列
        if (!tableData[targetRowIndex][picData.colIndex + 1]) {
          tableData[targetRowIndex][picData.colIndex + 1] = picData.url;
          imgs.push(picData.colIndex + 1);
        } else if (!tableData[targetRowIndex][picData.colIndex + 2]) {
          // 向上查找空位
          tableData[targetRowIndex][picData.colIndex + 2] = picData.url;
          imgs.push(picData.colIndex + 2);
        } else if (!tableData[targetRowIndex][picData.colIndex - 1]) {
          // 向下查找空位
          tableData[targetRowIndex][picData.colIndex - 1] = picData.url;
          imgs.push(picData.colIndex - 1);
        } else {
          // 替换默认位置
          const prevColIndex = Math.max(0, picData.colIndex + 1);
          tableData[targetRowIndex][prevColIndex] = picData.url;
          imgs.push(prevColIndex);
        }
      });
    }

    // 返回处理后的表格配置
    return {
      headers, // 表头
      tableData, // 表格数据
      imgs, // 图片列索引
      fileName: dataItem.fileName, // 文件名
      sheetName: dataItem.sheetName, // 表名
      maxOmit: tableData.length - 4, // 最大省略行号
      minOmit: 20, // 最小省略行号
      omit: tableData.length > 20, // 是否省略
      headersPosition, // 表头位置
    };
  });
  console.log(tableList);
};
const noPageList = async () => {
  const { data } = await api.default.common.importTemplate.noPageList({
    moduleId: route.query?.moduleId,
  });
  temList.value = data || [];
  fieldObj.value = data?.[0];
};
// 组件挂载时初始化数据
onMounted(() => {
  noPageList();
});
const imgType = (item, row, colIndex) => {
  return (
    row[colIndex] &&
    item.imgs.includes(colIndex) &&
    (row[colIndex].includes("http") || row[colIndex].includes("https"))
  );
};
const handleChange = (file) => {
  fileList.value.push(file);
  // 使用防抖函数
  adjustTableHeight();
};
const previewExcel = async () => {
  if (!fileList.value.length) return;
  const formData = new FormData();
  fileList.value.forEach((item) => {
    formData.append("files", item.raw);
  });
  const { data } = await api.default.common.importTemplate.previewExcel(
    formData
  );
  conentData.value = data;
  list();
};
const adjustTableHeight = debounce(() => {
  previewExcel();
}, 500);
/**
 * 判断行是否应该显示
 * @param {Object} item - 表格配置项
 * @param {number} rowIndex - 行索引
 * @returns {boolean} 是否显示
 */
const isTypeOmit = (item, rowIndex) => {
  if (item.omit) {
    return rowIndex <= item.minOmit || rowIndex > item.maxOmit;
  }
  return true;
};

/**
 * 切换省略显示状态
 * @param {Object} item - 表格配置项
 */
const toggleOmit = (item) => {
  if (item.tableData.length < 20) return; // 少于20行不显示省略
  item.omit = !item.omit;
};
/**
 * 规则匹配函数 - 分析表关联规则并构建规则集合
 * @param {string} targetRule - 目标规则，格式如 "2:1"
 * @returns {Array} 完整的规则链集合
 */
const ruleMatching = (targetRule, rules) => {
  try {
    if (!targetRule || typeof targetRule !== "string") {
      return [];
    }

    // 解析目标规则，格式为 "表索引:列索引"
    const [targetTable, targetColumn] = targetRule.split(":").map(Number);

    if (isNaN(targetTable) || isNaN(targetColumn)) {
      return [];
    }

    // 获取主表索引
    const masterTable = fieldObj.value.mainTableIndex;

    // 如果目标表就是主表，直接返回
    if (targetTable === masterTable) {
      return [
        {
          fromTable: masterTable,
          fromColumn: targetColumn,
          toTable: masterTable,
          toColumn: targetColumn,
          rule: rules,
          type: "target",
        },
      ];
    }

    // 查找从主表到目标表的完整规则链
    const ruleChain = findCompleteRuleChain(masterTable, targetTable);

    if (ruleChain.length === 0) {
      throw new Error(
        `未找到规则${targetRule}从主表${masterTable}到目标表${targetTable}的完整规则链`
      );
    }
    // 构建完整的规则集合
    const ruleCollection = buildRuleCollection(ruleChain, targetColumn, rules);

    return ruleCollection;
  } catch (error) {
    throw new Error(error.message);
  }
};

/**
 * 查找从起始表到目标表的完整规则链
 * @param {number} fromTable - 起始表索引
 * @param {number} toTable - 目标表索引
 * @returns {Array} 规则链
 */
const findCompleteRuleChain = (fromTable, toTable) => {
  const rules = fieldObj.value.multiSheetRules
    ? fieldObj.value.multiSheetRules.split(",")
    : [];
  if (!rules.length) return [];
  // 构建规则图
  const ruleGraph = buildRuleGraph(rules);

  // 使用 BFS 查找路径
  const visited = new Set();
  const queue = [
    {
      table: fromTable,
      path: [],
      usedRules: new Set(), // 记录已使用的规则，避免循环
    },
  ];

  while (queue.length > 0) {
    const { table, path, usedRules } = queue.shift();

    if (visited.has(table)) continue;
    visited.add(table);

    // 找到目标表，返回路径
    if (table === toTable) {
      return path;
    }

    // 查找所有与当前表关联的规则
    if (ruleGraph[table]) {
      for (const [targetTableKey, ruleInfo] of Object.entries(
        ruleGraph[table]
      )) {
        const targetTableNum = parseInt(targetTableKey);
        const ruleKey = `${table}:${ruleInfo.fromColumn}=${targetTableNum}:${ruleInfo.toColumn}`;
        const reverseRuleKey = `${targetTableNum}:${ruleInfo.toColumn}=${table}:${ruleInfo.fromColumn}`;

        // 避免使用重复规则（防止循环）
        if (usedRules.has(ruleKey) || usedRules.has(reverseRuleKey)) {
          continue;
        }

        const newPath = [
          ...path,
          {
            fromTable: table,
            fromColumn: ruleInfo.fromColumn,
            toTable: targetTableNum,
            toColumn: ruleInfo.toColumn,
            rule: ruleKey,
          },
        ];

        const newUsedRules = new Set(usedRules);
        newUsedRules.add(ruleKey);

        queue.push({
          table: targetTableNum,
          path: newPath,
          usedRules: newUsedRules,
        });
      }
    }
  }

  return [];
};

/**
 * 构建规则图
 * @param {Array} rules - 规则数组
 * @returns {Object} 规则图
 */
const buildRuleGraph = (rules) => {
  const graph = {};

  rules.forEach((rule) => {
    const [left, right] = rule.split("=");
    const [leftTable, leftCol] = left.split(":").map(Number);
    const [rightTable, rightCol] = right.split(":").map(Number);

    // 添加到图中（双向）
    if (!graph[leftTable]) graph[leftTable] = {};
    if (!graph[rightTable]) graph[rightTable] = {};

    graph[leftTable][rightTable] = {
      fromColumn: leftCol,
      toColumn: rightCol,
      rule: `${leftTable}:${leftCol}=${rightTable}:${rightCol}`,
    };

    graph[rightTable][leftTable] = {
      fromColumn: rightCol,
      toColumn: leftCol,
      rule: `${rightTable}:${rightCol}=${leftTable}:${leftCol}`,
    };
  });

  return graph;
};

/**
 * 构建规则集合
 * @param {Array} ruleChain - 规则链
 * @param {number} targetColumn - 目标列索引
 * @returns {Array} 规则集合
 */
const buildRuleCollection = (ruleChain, targetColumn, rules) => {
  const collection = [];

  // 添加规则链中的每一步
  ruleChain.forEach((step, index) => {
    collection.push({
      step: index + 1,
      fromTable: step.fromTable,
      fromColumn: step.fromColumn,
      toTable: step.toTable,
      toColumn: step.toColumn,
      rule: step.rule,
      type: "link",
    });
  });

  // 添加最终的目标规则
  const lastStep = ruleChain[ruleChain.length - 1];
  collection.push({
    step: ruleChain.length + 1,
    fromTable: lastStep.toTable,
    fromColumn: targetColumn,
    toTable: lastStep.toTable,
    toColumn: targetColumn,
    rule: rules || `${lastStep.toTable}:${targetColumn}`,
    type: "target",
  });

  return collection;
};

/**
 * 获取所有字段的规则分析结果
 */
const analyzeAllRules = () => {
  const analysisResults = {};

  fieldObj.value.importTemplateDetailsList.forEach((field) => {
    if(!field.rules) return 
    const regex = /(\d+:\d+)/;
    const regex_j = /(\d+#\d+)/;
    const regex_s = /(\d+\|\d+)/;
    const globalRegex = /(\d+(?::\d+)?)(?:\(([\*\|]\^(\d+))\))?/;
    let globalrules = "";
    const strArr = globalRegex.exec(field.rules);
    if (strArr && strArr[2]) {
      globalrules = strArr[1].includes(":")
        ? strArr[1]
        : fieldObj.value.mainTableIndex + ":" + strArr[1];
    }
    let rules = globalrules ? globalrules : field.rules.match(regex)?.[0];
    let rules_j = field.rules?.match(regex_j)?.[0];
    let rules_s = field.rules?.match(regex_s)?.[0];
    if (rules) {
      // 跨表字段，分析规则链
      const ruleCollection = ruleMatching(rules, field.rules);
      analysisResults[field.fieldNameEn] = {
        fieldName: field.fieldName,
        rules: field.rules,
        ruleCollection: ruleCollection,
        isValid: ruleCollection.length > 0,
      };
    } else if (rules_j) {
      //特殊#
      const [left, right] = rules_j.split("#");
      analysisResults[field.fieldNameEn] = {
        fieldName: field.fieldName,
        rules: field.rules,
        ruleCollection: [
          {
            step: 1,
            toTable: Number(left),
            toColumn: Number(right),
            rule: field.rules,
            type: "target",
          },
        ],
        isValid: true,
      };
    } else if (rules_s) {
      const [left, right] = rules_s.split("|");
      analysisResults[field.fieldNameEn] = {
        fieldName: field.fieldName,
        rules: field.rules,
        ruleCollection: [
          {
            step: 1,
            fromColumn: Number(left),
            toTable: fieldObj.value.mainTableIndex,
            toColumn: Number(right),
            rule: field.rules,
            type: "target",
          },
        ],
        isValid: true,
      };
    } else {
      // 主表字段
      analysisResults[field.fieldNameEn] = {
        fieldName: field.fieldName,
        rules: rules,
        ruleCollection: [
          {
            step: 1,
            fromTable: fieldObj.value.mainTableIndex,
            fromColumn: Number(rules),
            toTable: fieldObj.value.mainTableIndex,
            toColumn: Number(rules),
            rule: `${fieldObj.value.mainTableIndex}:${rules}`,
            type: "direct",
          },
        ],
        isValid: true,
      };
    }
  });

  return analysisResults;
};

const handleCheckChange = (data) => {
  fieldObjList.value = temList.value.filter((item) =>
    data.includes(item.templateCode)
  );
};
const handleTemplateClick = (item) => {
  fieldObj.value = item;
};
const onSave = () => {
  try {
    const obj = {};
    const arr = fieldObjList.value.length
      ? fieldObjList.value
      : [fieldObj.value];
    arr.forEach((item) => {
      fieldObj.value = item;
      obj[item.templateCode] = onData();
    });
    console.log(obj);
    
  } catch (error) {
    ElMessage.error(error.message);
  }
};
/**
 * 改进的 onSave 函数 - 包含规则分析
 */
const onData = () => {
  try {
    // 首先分析所有规则
    const ruleAnalysis = analyzeAllRules();
    // 然后生成数据
    const masterTableIndex = fieldObj.value.mainTableIndex - 1;
    const data = tableList.value[masterTableIndex];

    if (!data) {
      console.error("主表数据不存在");
      return;
    }

    const list = data.tableData.slice(data.headersPosition);
    const saveDate = [];

    // 处理每一行数据
    list
      .filter((item) => {
        const arr = item.filter((it) => it);
        return arr.length > fieldObj.value.leastData && !arr.includes("合计");
      })
      .forEach((item, rowIndex) => {
        const arr = item.slice(1); // 跳过序号列

        // 跳过空行
        if (arr.every((it) => it === "" || it === null || it === undefined))
          return;

        const obj = {};

        // 临时存储当前处理的行，供 ruleMatching 使用
        window.currentProcessingRow = arr;

        // 处理每个字段
        fieldObj.value.importTemplateDetailsList.forEach((field) => {
          console.log(field.rules);
          
          if (field.rules && isNaN(Number(field.rules))) {
            // 跨表字段 - 格式如 "3:5" 表示取表3第5列
            obj[field.fieldNameEn] = executeRuleChain(
              ruleAnalysis[field.fieldNameEn].ruleCollection,
              arr
            );
          } else if(!field.rules){
             obj[field.fieldNameEn] = null
          } else {
            // 主表字段 - 直接取主表对应列
            const columnIndex = Number(field.rules);
            obj[field.fieldNameEn] = arr[columnIndex] || "";
          }
        });

        // 清理临时存储
        delete window.currentProcessingRow;

        saveDate.push(obj);
      });
    return saveDate;
  } catch (error) {
    ElMessage.error(error.message);
  }
};
const executeRuleChain = (ruleCollection, arr, arrIndex) => {
  try {
    const fieldArr = [
      {
        find: [0, ...arr],
        fromTable: fieldObj.value.mainTableIndex,
      },
    ];
    let str = "";
    const singStr = ruleCollection.at(-1).rule;
    // 更新正则表达式，添加对'#'操作符和'17(*^1)'格式的支持
    const singleRegex =
      /(\d+:\d+\(\*\^\d+\))|(\d+\(\*\^\d+\))|(\d+:\d+#\d+)|(\d+:\d+)|(\d+#\d+)|(\d+)|([+\-*|/,])/g;
    const match = singStr.match(singleRegex);
    ruleCollection.forEach((rule) => {
      const list = tableList.value[rule.toTable - 1].tableData;
      if (
        rule.fromTable === fieldObj.value.mainTableIndex &&
        rule.type === "link"
      ) {
        let find = list.find((item) => {
          const itemSeq = item.slice(1);
          return itemSeq[rule.toColumn] === arr[rule.fromColumn];
        });
        find &&
          fieldArr.push({
            find,
            fromTable: rule.toTable,
          });
      } else if (rule.type === "link") {
        const parameter = fieldArr.at(-1).find.slice(1);
        let find = list.find((item) => {
          const itemSeq = item.slice(1);
          return itemSeq[rule.toColumn] === parameter[rule.fromColumn];
        });
        find &&
          fieldArr.push({
            find,
            fromTable: rule.toTable,
          });
      } else if (rule.type === "target") {
        const parameter = fieldArr.at(-1).find.slice(1);
        let numStr = "";
        if (match && match.length >= 1) {
          let numArr = match
            .map((item, index) => {
              let numBer = "";
              if (["+", "-", "*", "/", "|", ","].includes(item)) {
                return item;
              } else {
                // 检查是否包含'#'操作符（固定取指定表指定列，默认第一行）
                if (item.includes("#")) {
                  const mapSplit = item.split("#");
                  if (item.includes(":")) {
                    const [str, strIndex] = mapSplit;
                    const [tableIndex, columnIndex] = str
                      .split(":")
                      .map(Number);
                    const tableData =
                      tableList.value[tableIndex - 1]?.tableData || [];
                    if (tableData && tableData.length > 0) {
                      numBer =
                        tableData[columnIndex - 1].slice(1)[strIndex] || numBer;
                    }
                    return numBer;
                  }

                  const [tableIndex, columnIndex] = mapSplit.map(Number);
                  // 获取指定表的数据
                  const tableData = tableList.value[0];
                  if (tableData && tableData.tableData.length > 0) {
                    // 默认取第一行数据（跳过表头）
                    const rowData =
                      tableData.tableData[tableData.headersPosition || 0];
                    if (rowData) {
                      // 跳过序号列，返回指定列的数据
                      return rowData.slice(1)[columnIndex] || numBer;
                    }
                  }
                  return numBer;
                }
                // 原有逻辑，处理':'操作符
                else {
                  let rules = item;
                  // 检查是否包含特殊格式 "1:17(*^1)"
                  let symbol = "";
                  let position = "";
                  if (item.includes("^")) {
                    const globalRegex =
                      /(\d+(?::\d+)?)(?:\(([\*\|]\^(\d+))\))?/;
                    const strArr = globalRegex.exec(item);
                    symbol = strArr[2].split("^")[0];
                    position = strArr[2].split("^")[1] - 1;
                    rules = strArr[1].includes(":")
                      ? strArr[1]
                      : fieldObj.value.mainTableIndex + ":" + strArr[1];
                  }
                  // 普通':'操作符处理逻辑
                  const segmentation = rules.split(":");
                  const data = fieldArr.find((it) => {
                    return it.fromTable === Number(segmentation[0]);
                  });
                  if (index > 0) {
                    const val = match[index - 1];
                    if (["+", "-"].includes(val)) {
                      numBer = 0;
                    } else if (["*", "/"].includes(val)) {
                      numBer = 1;
                    }
                  }
                  if (data) {
                    if (symbol) {
                      return (
                        data.find?.slice(1)?.[segmentation[1]]?.split(symbol)?.[
                          Number(position)
                        ] || numBer
                      );
                    }
                    return data.find.slice(1)[segmentation[1]] || numBer;
                  } else {
                    try {
                      if (arrIndex) {
                        return "";
                      }
                      if (!isNaN(Number(item))) {
                        return arr[item] || 0;
                      }
                      return (
                        executeRuleChain(ruleMatching(item), arr, 1) || numBer
                      );
                    } catch (error) {
                      throw new Error(error.message);
                    }
                  }
                }
              }
            })
            .filter((item) => item);
          const newArr = [];
          let i = 0;
          while (i < numArr.length) {
            // 检查当前项是否是'|'操作符
            if (numArr[i] === "|") {
              i++;
              continue;
            }
            // 检查下一项是否是'|'操作符
            if (i + 1 < numArr.length && numArr[i + 1] === "|") {
              // 优先使用左侧值，如果左侧值为空则使用右侧值
              const leftValue = numArr[i];
              const rightValue = numArr[i + 2]; // 跳过'|'

              // 如果左侧值存在且不为空，使用左侧值
              if (
                leftValue !== undefined &&
                leftValue !== null &&
                leftValue !== ""
              ) {
                newArr.push(leftValue);
              } else if (rightValue !== undefined) {
                // 否则使用右侧值
                newArr.push(rightValue);
              }

              // 跳过右侧值
              i += 3;
            } else {
              // 普通项直接添加
              newArr.push(numArr[i]);
              i++;
            }
          }
          if (newArr.find((item) => ["+", "-", "*", "/"].includes(item))) {
            numStr = calculateWithSteps(newArr).result;
          } else {
            const jionStr = newArr.find((item) => [","].includes(item))
              ? "|;"
              : " ";
            numStr = newArr
              .filter((item) => item !== "" && item !== ",")
              .join(jionStr);
          }
        }
        str = numStr || "";
      }
    });
    return str;
  } catch (error) {
    throw new Error(error.message);
  }
};
function calculateWithSteps(tokens) {
  // 将字符串数字转换为数字类型
  const parsedTokens = tokens.map((token) => {
    if (["+", "-", "*", "/"].includes(token)) {
      return token;
    } else {
      return parseFloat(token);
    }
  });

  const precedence = {
    "*": 2,
    "/": 2,
    "+": 1,
    "-": 1,
  };

  // 转换为后缀表达式
  function toPostfix(tokens) {
    const output = [];
    const operators = [];

    tokens.forEach((token) => {
      if (typeof token === "number") {
        output.push(token);
      } else {
        while (
          operators.length > 0 &&
          precedence[operators[operators.length - 1]] >= precedence[token]
        ) {
          output.push(operators.pop());
        }
        operators.push(token);
      }
    });

    while (operators.length > 0) {
      output.push(operators.pop());
    }

    return output;
  }

  const postfix = toPostfix(parsedTokens);

  // 计算后缀表达式并记录步骤
  const stack = [];
  const steps = [];

  postfix.forEach((token) => {
    if (typeof token === "number") {
      stack.push(token);
    } else {
      const right = stack.pop();
      const left = stack.pop();

      let result;
      switch (token) {
        case "+":
          result = left + right;
          break;
        case "-":
          result = left - right;
          break;
        case "*":
          result = left * right;
          break;
        case "/":
          result = left / right;
          break;
      }

      steps.push({
        operation: token,
        left: left,
        right: right,
        result: result,
      });

      stack.push(result);
    }
  });

  return {
    original: tokens,
    postfix: postfix,
    steps: steps,
    result: stack[0],
  };
}
</script>

<style lang="scss" scoped>
:deep() .el-input__inner {
  color: red;
}
/* 主容器样式 */
.common-wrap {
  padding: 20px;
}

/* 区域标题样式 */
.section-title {
  margin: 5px 0;
  font-size: 16px;
}

.flex-center {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.flex-column {
  display: flex;
  align-items: center;
  flex-direction: column;
}

/* 模板导航栏样式 */
.nav-template,
.flex-weap {
  display: flex;
  flex-wrap: wrap;
}

/* 字段模板样式 */
.field-template {
  display: flex;
  justify-content: space-between;
  /* align-items: flex-end; */
  text-align: center;
  margin-bottom: 10px;
}

/* 字段项样式 */
.field-item {
  margin-right: 10px;
}

/* 字段标签样式 */
.field-label {
  color: #409eff;
  /* margin-right: 5px; */
}

/* 字段值样式 */
.field-value {
  color: red;
}

/* 设置图标样式 */
.settings-icon {
  cursor: pointer;
  display: flex;
}

.settings-icon .el-icon {
  font-size: 18px;
  color: #409eff;
}

/* 表格容器样式 */
.table-container {
  margin-bottom: 20px;
}

/* 表格标题样式 */
.table-title {
  display: flex;
  align-items: center;
  margin: 5px 0;
}

/* 标题项样式 */
.title-item {
  margin-right: 10px;
}

/* 高亮文本样式 */
.highlight-text {
  color: red;
}

/* 索引数字样式 */
.index-number {
  color: red;
  padding: 0 5px;
}

/* 切换按钮样式 */
.toggle-button {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin: 0 10px;
}

.toggle-button .el-icon {
  font-size: 18px;
}

/* 范围控制样式 */
.range-control {
  display: flex;
  align-items: center;
}

/* 范围标签样式 */
.range-label {
  margin: 0 10px;
}

/* 范围输入框样式 */
.range-input {
  width: 70px;
}

/* 范围分隔符样式 */
.range-separator {
  margin: 0 10px;
}

/* Element表格样式 */
.el-table {
  font-size: 12px;
}

.el-table__header {
  background-color: #f5f7fa;
}

:deep() .el-table__row {
  height: 30px;
}

/* 原生表格样式 */
.native-table {
  font-size: 13px;
  position: relative;
  border-collapse: collapse;
  border-color: #cccccc52;
  border: 1px solid #cccccc52;
  width: 100%;
}

/* 表头固定样式 */
.native-table thead {
  position: sticky; /* 粘性定位 */
  top: 0; /* 固定在顶部 */
  background: #e5e5e5; /* 背景色 */
  height: 30px; /* 高度 */
}

/* 表头单元格样式 */
.table-header {
  max-width: 160px;
  overflow: hidden;
  text-align: left;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0 10px;
  font-weight: bold;
}

/* 表格单元格样式 */
.table-cell {
  max-width: 160px;
  overflow: hidden;
  text-align: left;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0 10px;
  border: 1px solid #cccccc52;
}

/* 列索引样式 */
.column-index {
  margin-right: 5px;
  color: red;
}

/* 行样式 */
.table-row {
  height: 30px !important;
  line-height: 7px;
}

/* 预览图片样式 */
.preview-image {
  width: 25px;
  height: 25px;
}

/* 标题元素通用样式 */
h5,
h6 {
  margin: 5px 0;
  padding: 0;
}
</style>